package com.study.zouchao.superproject.myreceivedtask;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.login.model.entity.User;
import com.study.zouchao.superproject.logininterceptor.LoginStatusUtil;
import com.study.zouchao.superproject.mypublishtask.IPublishTaskListContract;
import com.study.zouchao.superproject.mypublishtask.adapter.MyPublishListAdapter;
import com.study.zouchao.superproject.mypublishtask.model.MyPublishTaskListModel;
import com.study.zouchao.superproject.mypublishtask.model.entity.MyPublishTaskListResult;
import com.study.zouchao.superproject.myreceivedtask.adapter.MyReceivedListAdapter;
import com.study.zouchao.superproject.myreceivedtask.model.MyReceivedTaskListModel;
import com.study.zouchao.superproject.myreceivedtask.model.entity.FinishResult;
import com.study.zouchao.superproject.myreceivedtask.model.entity.MyReceivedTaskListResult;
import com.study.zouchao.superproject.util.App;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/6/25.
 */

public class MyReceivedPresenter implements IReceivedTaskListContract.IReceivedTaskListPresenter, MyReceivedListAdapter.IRvItemClickListener {
    private IReceivedTaskListContract.IReceivedTaskListView  mView;
    private Context mContext;
    private List<MyReceivedTaskListResult.TaskItemBean> mData;
    private Subscription mSupConn, mSupFinishTask;
    //用户操作：下拉刷新
    private static final String ACTION_REFRESHING = "ACTION_REFRESHING";
    //用户操作：上滑更多
    private static final String ACTION_SEE_MORE = "ACTION_SEE_MORE";
    private int mPageSize = 5;
    private int mPageIndex = 1;
    private int mTotalSize = 0;
    private MyReceivedListAdapter mAdapter;
    //正在加载数据
    private boolean mIsLoadingData = false;
    private MyReceivedTaskListModel mConnModel;

    private String mUserName = "zc";

    public MyReceivedPresenter(Context context, IReceivedTaskListContract.IReceivedTaskListView view) {
        mContext = context;
        mConnModel = new MyReceivedTaskListModel();
//        mCacheModel = new TravelCacheModel();
        mView = view;
        init();
    }
    private void init() {
        mData = new ArrayList<>();
        mAdapter = new MyReceivedListAdapter(mContext, mData);
    }

    @Override
    public void onRefreshingData() {
        conn(ACTION_REFRESHING);

    }
    private void conn(final String action) {
        if (!isValidUserAction(action)) {
            mView.showSnackBar("用户操作有误");
//            Toast.makeText(mContext, "用户操作有误", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> requestParams = getRequestParams(action);
        if (requestParams==null || requestParams.isEmpty()) {
            mView.showSnackBar("用户操作有误");
//            ToastUtils.showShort(App.getAppContext(), "请求参数错误、请稍后再试");
            mView.showSnackBar("请求参数错误、请稍后再试");
            return;
        }
        toggleLoading(action, true);
        mIsLoadingData = true;
        mSupConn = mConnModel.listMyReceivedTaskList(requestParams)
                .subscribe(new Action1<MyReceivedTaskListResult>() {
                    @Override
                    public void call(MyReceivedTaskListResult taskListResult) {
                        judgeConnResult(taskListResult, action);
                        toggleLoading(action, false);
                        mIsLoadingData = false;
                        mView.showSnackBar("我接受的任务列表获取成功");
//                        ToastUtils.showShort(App.getAppContext(), "获取接受列表陈宫"+taskListResult.toString());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        failGetList(throwable, action);
                        toggleLoading(action, false);
                        mIsLoadingData = false;
                        throwable.printStackTrace();
                    }
                });
    }

    private void failGetList(Throwable throwable, String action) {
        throwable.printStackTrace();
        ToastUtils.showLong(mContext, throwable.getMessage());
//        if (action.equals(ACTION_REFRESHING))
//            loadDataFromCache();
    }


    private void judgeConnResult(MyReceivedTaskListResult taskListResult, final String action) {
        switch (taskListResult.getCode()) {
            case 21501 :
                successGetList(taskListResult, action);
                break;
            default:
                mView.showSnackBar("获取数据失败、请稍后再试...");
                break;
        }
    }


    private void successGetList(MyReceivedTaskListResult result, String action) {
        if (action.equals(ACTION_REFRESHING)) {
            mData.clear();
//            saveNewData2Cache(result.getResult());
        }
        mTotalSize = result.getPageSize();
        Log.d("pageSize", result.getPageSize()+"");
        List<MyReceivedTaskListResult.TaskItemBean> newData = result.getData();
        mData.addAll(newData);
//
        mAdapter.notifyDataSetChanged();
    }


    private Map<String, String> getRequestParams(String action) {
        User userBean = getLoginedUserBean();
        if (userBean==null || StringUtils.isEmpty(userBean.getUserName()))   return null;

        if(action.equals(ACTION_REFRESHING)) mPageIndex = 1;
        if (action.equals(ACTION_SEE_MORE))  mPageIndex += 1;

        Map<String, String> params = new HashMap<>();

        params.put("userName", userBean.getUserName());
        params.put("currentRows", mPageSize+"");
        params.put("currentPage", mPageIndex+"");
        return params;
    }


    private User getLoginedUserBean() {
        User userBean = LoginStatusUtil.getLoginDataByBean(mContext);
        //事实上 不可能为空
        if (userBean==null) {
            return null;
        }
        return userBean;
    }

    private void toggleLoading(String userAction, boolean isShow) {
        if (userAction.equals(ACTION_REFRESHING))   mView.showRefreshingLoading(isShow);
        if(userAction.equals(ACTION_SEE_MORE))      mView.showSeeMoreLoading(isShow);
    }


    private boolean isValidUserAction(String action) {
        return (action!=null) && (action.equals(ACTION_REFRESHING) || action.equals(ACTION_SEE_MORE));
    }


    @Override
    public void loadSeeMore() {
        if (mIsLoadingData)      return;
        //无数据的情况只能下拉刷新不允许上滑更多   1是footView
        if (mAdapter.getItemCount()<=1)   return;
        if ((mPageIndex) >= mTotalSize) {
//            ToastUtils.showShort(App.getAppContext(), "无更多数据");
            mView.showSnackBar("Warn！！无更多数据！！");
            return;
        }
        conn(ACTION_SEE_MORE);
    }

    @Override
    public void initRecyclerView(RecyclerView rv) {
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mData = new ArrayList<>();
        //为RecyclerView加Adapter
        mAdapter = new MyReceivedListAdapter(mContext, mData);
        View footLoadingView = LayoutInflater.from(mContext).inflate(R.layout.footview_recyclerview, rv, false);
        mAdapter.setFooterView(footLoadingView);
        mAdapter.setOnItemClickListener(this);
        mView.setSeeMoreLoading(footLoadingView);
        rv.setAdapter(mAdapter);
        //添加上滑更多监听器
        //请求数据
        conn(ACTION_REFRESHING);
    }


    public void onClickFinishTask(int taskId) {
        HashMap<String, String> params = getReqParams(taskId);
        if (params == null) {
            return;
        }
        mSupFinishTask = mConnModel.finishTask(getReqParams(taskId))
                .subscribe(new Action1<FinishResult>() {
                    @Override
                    public void call(FinishResult finishResult) {
                        judgeFinishTaskResult(finishResult);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                });
    }

    private void judgeFinishTaskResult(FinishResult finishResult) {
        if (finishResult == null)   return;
        switch (finishResult.getCode()) {
            case 29003 :
                onRefreshingData();
                break;
            default:
                onFailureFinishTask(finishResult);
                break;
        }
        mView.showSnackBar(finishResult.getMessage());
    }

    private void onFailureFinishTask(FinishResult finishResult) {

    }

    @Nullable
    private HashMap<String, String> getReqParams(int taskId) {
        User userBean = getLoginedUserBean();
        if (userBean==null || StringUtils.isEmpty(userBean.getUserName()))   return null;
        HashMap<String, String> params = new HashMap<>();
        params.put("userName", userBean.getUserName());
        params.put("taskId", taskId+"");
        return params;
    }

    @Override
    public void onItemClick(View v, int taskId) {
//        ToastUtils.showShort(App.getAppContext(), "妈的。。点击事件呢");
        onClickFinishTask(taskId);
    }

    @Override
    public void onDestroyPresente() {
        if (mSupConn!=null && !mSupConn.isUnsubscribed())    mSupConn.unsubscribe();
        if (mSupFinishTask!=null && !mSupFinishTask.isUnsubscribed())    mSupFinishTask.unsubscribe();
    }
}
